<template>
  <div class="content">
    <div class="topBox" ref="topBox">
      <div class="title">
        标签管理
        <span>
          <t-button class="hoverBlue" theme="primary" @click="handleAddEdit(true, {})" v-permission="['tag:save']">
            <template #icon>
              <svg-icon
                  :name="'icon-add'"
                  class-name="add-svg-icon"
              ></svg-icon>
            </template>
            新增标签
          </t-button>
          <t-dropdown class="batch" trigger="click" @click="clickHandler">
            <t-space>
              <t-button>
                <svg-icon
                    :name="'icon-batch'"
                    class-name="batch-svg-icon"
                ></svg-icon>
                <span class="name">批量操作</span>
                <svg-icon
                    :name="'icon-batchDown'"
                    class-name="batch-svg-icon"
                ></svg-icon>
              </t-button>
            </t-space>
                        <template #dropdown>
                <t-dropdown-menu>
                  <t-dropdown-item :value="1" :disabled="hasPermission('tag:import')">
                    <template #prefixIcon>
                      <svg-icon :name="'icon-exportIn'"></svg-icon>
                    </template>
                    <span>批量导入</span>
                  </t-dropdown-item>
                  <t-dropdown-item :value="2" :disabled="tableState.tableData.length === 0 || hasPermission('tag:export')">
                    <template #prefixIcon>
                      <svg-icon :name="'icon-export'"></svg-icon>
                    </template>
                    <span>批量导出</span>
                  </t-dropdown-item>
                  <t-dropdown-item :value="3" :disabled="selectedRowKeys.length === 0 || hasPermission('tag:delete')">
                    <template #prefixIcon>
                      <svg-icon :name="'icon-batchDel'"></svg-icon>
                    </template>
                    <span>批量删除</span>
                  </t-dropdown-item>
                </t-dropdown-menu>
              </template>
          </t-dropdown>
        </span>
      </div>
      <div class="line"></div>
      <div class="formBox">
        <t-form
            ref="form"
            :data="formData"
            :layout="'inline'"
            scroll-to-first-error="smooth"
        >
          <t-form-item label="标签名称" name="tagName" :label-width="58">
            <t-input v-model="formData.tagName" placeholder="请输入标签名称"></t-input>
          </t-form-item>

          <t-form-item label="匹配侧" name="type" :label-width="46">
            <t-select v-model="formData.type" placeholder="请选择匹配侧">
              <t-option key="0" label="座席侧" value="0" />
              <t-option key="1" label="用户侧" value="1" />
            </t-select>
          </t-form-item>

          <t-form-item class="formHandleBox">
            <t-space size="small" style="gap: 10px;">
              <t-button class="queryBtn hoverBlue" @click="handleQuery(1)">查询</t-button>
              <t-button class="resetBtn hoverLightBlue" @click="handleReset">重置</t-button>
            </t-space>
          </t-form-item>
        </t-form>
      </div>

    </div>
    <div class="tableBox">
      <div style="position: relative">
        <t-table
            :height="tableHeight"
            ref="tableRef"
            row-key="id"
            :data="tableState.tableData"
            :columns="tableState.columns"
            :selected-row-keys="selectedRowKeys"
            @select-change="handleSelectChange"
        >
          <template #handle="{ row }">
            <t-button theme="primary" class="rowEdit" @click="handleAddEdit(false, row)" v-permission="['tag:update']">
              <template #icon>
                <svg-icon
                    :name="'icon-rowEdit'"
                    class-name="row-svg-icon"
                ></svg-icon>
              </template>
              编辑
            </t-button>

            <t-button theme="primary" class="rowDel" @click="handleDel(row)" v-permission="['tag:delete']">
              <template #icon>
                <svg-icon
                    :name="'icon-rowDel'"
                    class-name="row-svg-icon"
                ></svg-icon>
              </template>
              删除
            </t-button>
          </template>
        </t-table>
        <div class="emptyBox" v-if="tableState.tableData.length === 0">
          <svg-icon
              :name="'icon-emptyTable'"
              class-name="emptyTable-svg-icon"
          ></svg-icon>
          <span>暂无数据</span>
        </div>
      </div>
    </div>
    <div class="footerBox">
      <t-pagination
          v-model="current"
          v-model:pageSize="pageSize"
          :pageSizeOptions="[10, 20, 30, 50]"
          :total="totalNum"
          size="small"
          show-jumper
          @page-size-change="onPageSizeChange"
          @current-change="onCurrentChange"
      />
    </div>
<!--    新增 ｜ 编辑-->
    <t-dialog
        v-if="saveVisible"
        v-model:visible="saveVisible"
        class="ruleDialog"
        width="483"
        :header="dialogTitle"
        :onClose="onClose"
    >
      <t-form
          ref="ruleForm"
          :data="ruleData"
          :label-align="'top'"
          :rules="AHEAD_RULES"
          @reset="ruleReset"
          @submit="ruleSubmit">
        <t-form-item label="标签名称" name="tagName">
          <t-input v-model="ruleData.tagName" placeholder="请输入标签名称"></t-input>
        </t-form-item>
        <t-form-item label="匹配侧" name="type">
          <t-radio-group v-model="ruleData.type">
            <t-radio value="0">座席侧</t-radio>
            <t-radio value="1">用户侧</t-radio>
          </t-radio-group>
        </t-form-item>
        <t-form-item class="handleRuleBox">
          <t-space size="small">
            <t-button theme="default" variant="base" type="reset">取消</t-button>
            <t-button class="hoverBlue" theme="primary" type="submit">保存</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>

    <!--    删除弹窗-->
    <t-dialog
        v-model:visible="delVisible"
        class="dialogDel"
        theme="info"
        width="431"
        :header="delHeader"
        :on-confirm="onClickConfirm"
    />
    <!--    导入组件-->
    <file-upload
        :openUpload="openUpload"
        @closeUpload="closeUpload"
        :templateText="'下载导入标签模板'"
        :downloadTemplate="downloadTemplate"
        :uploadUrl="'/tag/import'"
        :queryBody="queryBody"
        :accept="'.xlsx'"
    ></file-upload>
  </div>
</template>

<script lang="jsx" setup>
import {getCurrentInstance, nextTick, onMounted, onUnmounted, reactive, ref} from "vue";
import {MessagePlugin} from "tdesign-vue-next";
import {debounce, hasPermission} from "@/utils/tools";
import {
  tagList,
  newTag,
  detailTag,
  editTag,
  tagRowDel,
  tagsDel
} from '@/api/qualitySet/labelManager.js'
import cache from '@/utils/cache.js'
import FileUpload from "@/components/FileUpload/index.vue"
import {tagExport, tagReload} from "../../api/qualitySet/labelManager";

const pageInstance = getCurrentInstance()
// form 表单
const formData = reactive({
  projectId: JSON.parse(cache.getLocalstorage('authInfo'))['agencyId'],
  tagName: '',
  type: ''
});
const onSubmit = ({ validateResult, firstError }) => {
  if (validateResult === true) {
    MessagePlugin.success('提交成功');
  } else {
    console.log('Validate Errors: ', firstError, validateResult);
    MessagePlugin.warning(firstError);
  }
};

// 批量操作
const clickHandler = (data) => {
  if(data.value === 1) {
    onClickImport()
  } else if(data.value === 2) {
    onClickExport()
  } else {
    isBatchDel.value = true
    // delHeader.value = `您确认删除${selectedRowKeys.value.length}条数据吗？`
    delHeader.value = `是否确认删除？`
    delVisible.value = true
  }
};

// table
const tableState = reactive({
  tableData: [],
  columns: [
    {
      colKey: 'row-select',
      type: 'multiple',
      width: 90,
    },
    { colKey: '',title: '序号', cell:(h, { rowIndex }) => {
        {{
          return rowIndex + (current.value - 1) * pageSize.value + 1 >= 10
                ? rowIndex + (current.value - 1) * pageSize.value + 1
                : "0" + (rowIndex + (current.value - 1) * pageSize.value + 1)
        }}
      }
    },
    { colKey: 'id', title: '标签ID' },
    { colKey: 'tagName', title: '标签名称' },
    { colKey: 'type', title: '匹配侧', align: 'center', cell:(h, {row}) => {
        return row.type === 0
            ? <t-tag theme='success' variant="light-outline">
              座席侧
            </t-tag>
            : <t-tag theme='warning' variant="light-outline">
              用户侧
            </t-tag>
      } },
    { colKey: 'handle', title: '操作', align: 'center', width: 180 },
  ],
})
const selectedRowKeys = ref([])
const handleSelectChange = (value, ctx) => {
  selectedRowKeys.value = value;
};

// 分页
const current = ref(1);
const pageSize = ref(10);
const totalNum = ref(0)
const onPageSizeChange = (size) => {
  pageSize.value = size
  handleQuery()
};
const onCurrentChange = (index, pageInfo) => {
  current.value = index
  handleQuery()
};

// 查询
const handleQuery = (num) => {
  let data = {
    pageNo: num === 1 ? 1 : current.value,
    pageSize: pageSize.value,
    ...formData
  }
  tagList(data).then(res => {
    if (res.code === 0) {
      tableState.tableData = res.data.list
      current.value = res.data['currPage']
      pageSize.value = res.data['pageSize']
      totalNum.value = res.data['totalCount']
    }
  })
}
// 重置
const handleReset = () => {
  pageInstance.refs.form.reset()
}
// table 高度变化
const tableHeight = ref(0)
const getTableHeight = () => {
  nextTick(() => {
    const otherHeight = pageInstance.refs.topBox.offsetHeight
    const windowHeight = window.innerHeight
    tableHeight.value = windowHeight - otherHeight - 162
    console.log(tableHeight.value)
  })
}

// window窗口 变化
const getWindowInfo = () => {
  const info = {
    width: window.innerWidth,
    height: window.innerHeight
  }
  console.log(info)
  getTableHeight()
}
const resizeInfo = debounce(getWindowInfo, 0)
onMounted(() => {
  getTableHeight()
  window.addEventListener('resize', resizeInfo);
  handleQuery()
})
onUnmounted(() => {
  window.removeEventListener('resize', resizeInfo);
})

// 新增 dialog
const saveVisible = ref(false)
const dialogTitle = ref('')
const isNewTag = ref(false)
const handleAddEdit = (flag, row) => {
  dialogTitle.value = flag ? '新增标签' : '编辑标签'
  isNewTag.value = flag
  saveVisible.value = true

  // 编辑调用详情接口
  if(!flag) {
    detailTag(row.id).then(res => {
      ruleData.tagName = res.data.tagName
      ruleData.id = res.data.id
      ruleData.type = res.data.type.toString()
    })
  }
}
const AHEAD_RULES = {
  tagName: [ { required: true, message: '请输入标签名称' ,type: 'error', trigger: 'blur'}],
  type: [ { required: true, message: '请选择匹配侧' ,type: 'error', trigger: 'change'}]
}
const ruleData = reactive({
  projectId: JSON.parse(cache.getLocalstorage('authInfo'))['agencyId'],
  tagName: '',
  type: ''
});
const ruleSubmit = ({ validateResult, firstError }) => {
  if (validateResult === true) {

    if(isNewTag.value) { // 新增标签
      if(ruleData['id']) delete ruleData['id']
      newTag(ruleData).then(res => {
        if (res.code === 0) {
          saveVisible.value = false
          pageInstance.refs.ruleForm.reset()
          handleQuery()
          MessagePlugin.success('新增成功！')
        }
      })
    } else { // 编辑标签
      editTag(ruleData).then(res => {
        if (res.code === 0) {
          saveVisible.value = false
          pageInstance.refs.ruleForm.reset()
          handleQuery()
          MessagePlugin.success('编辑成功！')
        }
      })
    }
    // MessagePlugin.success('提交成功');
  } else {
    console.log('Validate Errors: ', firstError, validateResult);
    MessagePlugin.warning(firstError);
  }
};

// 删除
const delVisible = ref(false)
const rowId = ref()
const isBatchDel = ref(false) // 是否是批量删除
const delHeader = ref()
const handleDel = (row) => {
  isBatchDel.value = false
  delHeader.value = '是否删除此标签？'
  delVisible.value = true
  rowId.value = row.id
}

const onClickConfirm = () => {
  if(isBatchDel.value) {
    tagsDel(selectedRowKeys.value).then(res => {
      delVisible.value = false
      MessagePlugin.success('批量删除成功！');
      if(tableState.tableData.length - selectedRowKeys.value.length === 0) {
        current.value = current.value > 1 ? current.value - 1 : current.value
      }
      handleQuery()
    })
  } else {
    tagRowDel(rowId.value).then(res => {
      delVisible.value = false
      MessagePlugin.success('删除成功！');
      if(tableState.tableData.length - 1 === 0) {
        current.value = current.value > 1 ? current.value - 1 : current.value
      }
      console.log('curent', current.value)
      handleQuery()
    })
  }
}

const ruleReset = () => {
  pageInstance.refs.ruleForm.reset()
  saveVisible.value = false
}
const onClose = () => {
  pageInstance.refs.ruleForm.reset()
  saveVisible.value = false
}


// 导出
const onClickExport = () => {
  let data = {
    pageNo: current.value,
    pageSize: pageSize.value,
    ...formData
  }
  if(data.name === '') delete data.name
  if(data.matchingSide === '') delete data.matchingSide
  tagExport(data).then(res => {
    const url = URL.createObjectURL(res) //把blob对象转成一个url
    //创建一个a标签
    const a = document.createElement("a");
    a.href = url; //给a标签上的href属性加上地址
    a.download = "导出标签.xlsx"; //下载名称
    document.body.appendChild(a); //将a标签添加到文档对象中
    a.click(); //调点击事件
    document.body.removeChild(a); // 一次性的，用完就删除a标签
  }).catch(error => {
    console.log('批量导出', error)
  })
}
// 上传
const queryBody = ref({
  projectId:'0'
})
const openUpload = ref(false)
const onClickImport = () => {
  queryBody.value = {projectId: JSON.parse(cache.getLocalstorage('authInfo'))['agencyId']}
  openUpload.value = true
}
const closeUpload = (flag) => {
  openUpload.value = flag
  handleQuery()
}
// 导入模版下载
const downloadTemplate = () => {
  console.log('下载模版')
  tagReload().then(res => {
    console.log('wordReload', res)
    // let file = new File([res], ``);
    const url = URL.createObjectURL(res) //把blob对象转成一个url
    //创建一个a标签
    const a = document.createElement("a");
    a.href = url; //给a标签上的href属性加上地址
    a.download = `导入标签模板${new Date().getTime()}.xlsx`; //下载名称
    document.body.appendChild(a); //将a标签添加到文档对象中
    a.click(); //调点击事件
    document.body.removeChild(a); // 一次性的，用完就删除a标签
  })
}
</script>

<style lang="scss" scoped>
.content {
  position: relative;
  overflow: hidden;
  background-color: #EBECED !important;
  padding: 8px;
  .topBox {
    padding: 20px 20px 0 20px;
    background-color: rgba(255, 255,255, 1);
    border-radius: 4px 4px 0 0;
    .title {
      font-size: 16px;
      font-weight: 600;
      line-height: 24px;
      color: rgba(51, 51, 51, 1);
      text-align: left;
      vertical-align: top;
      :deep(.t-button) {
        float: right;
        width: 101px;
        height: 28px;
        opacity: 1;
        border-radius: 3px;
        background: rgba(30, 117, 254, 1);
        padding: 5px 16px 5px 16px;
        font-size: 12px;
        font-weight: 400;
        line-height: 16.8px;
        color: rgba(255, 255, 255, 1);
        text-align: left;
        .add-svg-icon {
          height: 16px;
          width: 16px;
          margin-right: 5px;
        }
      }
      .batch {
        float: right;
        margin-right: 10px;
        .t-button {
          width: 102px;
          height: 28px;
          background: rgba(227, 238, 255, 1);
          border-radius: 3px;
          border: 0.5px solid rgba(9.38399999999999, 95.71679999999998, 234.6, 1);
          padding: 6px 8px;
          vertical-align: middle;
          .batch-svg-icon {
            display: inline-block;
            height: 16px;
            width: 16px;
            color: rgba(30, 117, 254, 1);
          }
          .t-button__text {
            span {
              display: inline-block;
              margin: 0 4px;
              font-size: 12px;
              font-weight: 400;
              color: rgba(30, 117, 254, 1);
            }
          }
        }
        .t-button:hover {
          background: var(--Brand-Brand1-Light, #EDF2FD) !important;
          color: var(--Brand-Brand6-Hover, #458DFF) !important;
          border: 1px solid var(--Brand-Brand6-Hover, #458DFF) !important;
        }
      }

    }
    .line {
      height: 0;
      opacity: 1;
      background: rgba(204, 204, 204, 1);
      border: 1px solid rgba(239, 242, 245, 1);
      margin-top: 21px;
    }
    :deep(.t-form) {
      padding: 20px 0 20px 0;
      .t-form-inline {
        row-gap: 16px !important;
      }
      .t-form__item {
        width: 25%;
        height: 28px;
        margin-right: 0!important;
        padding-right: 20px;
        .t-input {
          height: 28px;
        }
        .t-range-input {
          height: 28px;
        }
        .t-form__label--right {
          text-align: left;
          padding-right: 0;
          font-size: 12px;
          font-weight: 400;
          color: rgba(0, 0, 0, 0.9);
        }
        .t-select__wrap {
          .t-input {
            height: 28px;
          }
        }
      }
      .t-form__item:nth-child(4) {
        padding-right: 0;
      }
      .formHandleBox {
        margin-left: auto;
        text-align: right;
        padding-right: 0;
        .t-space {
          margin-left: auto;
          justify-content: center;
          align-items: center;
          .queryBtn {
            border: none;
            width: 56px;
            height: 30px;
            opacity: 1;
            border-radius: 3px;
            background: rgba(30, 117, 254, 1);
            font-size: 12px;
            font-weight: 400;
            color: rgba(255, 255, 255, 1);
            text-align: center;
            border: none;
          }
          .resetBtn {
            width: 56px;
            height: 30px;
            opacity: 1;
            border-radius: 3px;
            background: rgba(236, 242, 254, 1);
            border: 0.5px solid rgba(30, 117, 254, 1);
            font-size: 12px;
            font-weight: 400;
            color: rgba(30, 117, 254, 1);
            text-align: center;
          }
        }
        .t-form__controls {
          margin-left: 0 !important;
        }
      }
    }
  }
  .tableBox {
    :deep(.t-table__header) {
      tr {
        th {
          padding: 7px 10px;
          box-sizing: border-box;
        }
        th:nth-child(1) {
          padding: 7px 5px 7px 65px;
        }
        th:nth-child(2) {
          padding-left: 0;
        }
      }
    }
    :deep(.t-table__body) {
      tr {
        td {
          padding: 6px 10px;
          box-sizing: border-box;
        }
        td:nth-child(1) {
          padding: 7px 5px 7px 65px;
        }
        td:nth-child(2) {
          padding-left: 0;
        }
      }
      .t-button {
        border: none;
        width: 56px;
        height: 26px;
        opacity: 1;
        border-radius: 3px;
        font-size: 13px;
        font-weight: 400;
        padding: 0;
        margin: 0 4px;
        .row-svg-icon {
          height: 12px;
          width: 12px;
          margin-right: 2px;
        }
      }
      .rowDel {
        background: rgba(255, 224, 224, 1);
        color: rgba(227, 77, 89, 1);
      }
      .rowConfig {
        background: rgba(255, 238, 224, 1);
        color: rgba(255, 153, 0, 1);
      }
      .rowEdit {
        background: rgba(227, 238, 255, 1);
        color: rgba(30, 117, 254, 1);
      }

      .t-tag {
        margin: 0 auto;
        width: 62px;
        height: 24px;
        opacity: 1;
        border-radius: 4px;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 5px 12px 5px 12px;
        font-size: 12px;
        font-weight: 400;
      }
      .t-tag--warning {
        background: rgba(255, 246, 230, 1);
        border: 1px solid rgba(255, 153, 0, 1);
        color: rgba(255, 153, 0, 1);
      }
      .t-tag--success {
        background: rgba(233, 246, 242, 1);
        border: 1px solid rgba(0, 184, 122, 1);
        color: rgba(0, 184, 122, 1);
      }
    }
  }
  :deep(.t-table__empty) {
    display: none;
  }
  .emptyBox {
    position: absolute;
    height: 116px;
    width: 69px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    .emptyTable-svg-icon {
      height: 62px;
      width: 69px;
    }
    span {
      font-size: 12px;
      font-weight: 400;
      color: rgba(92, 91, 91, 1);
    }
  }
}
.footerBox {
  background-color: rgba(255,255,255,1);
  width: calc(100% - 16px);
  position: absolute;
  bottom: 8px;
  overflow: hidden;
  border-radius: 0 0 4px 4px;
}
:deep(.ruleDialog .t-dialog__wrap .t-dialog__position .t-dialog) {
  padding: 22px 22px 18px 22px;
  border-radius: 6px;
  .t-dialog__footer {
    display: none !important;
  }
  .t-dialog__body {
    padding-bottom: 0;
    .t-form__item {
      margin-bottom: 16px;
    }
    .t-form__item:nth-child(3) {
      padding-top: 3px;
      margin-bottom: 0;
    }
    .t-input {
      height: 28px;
    }
    .t-radio__label {
      font-size: 12px;
      font-weight: 400;
      color: rgba(92, 91, 91, 1);
    }
  }
}
.handleRuleBox {
  :deep(.t-form__label) {
    font-size: 14px;
    font-weight: 400;
    color: rgba(227, 60, 100, 0.9);

  }
  :deep(.t-form__controls) {
    text-align: right;
  }
  :deep(.t-form__controls-content) {
    display: inline-block;
    position: absolute;
    right: 0;
  }
  .t-button--theme-default {
    background-color: white;
    border: none;
    width: 60px;
    height: 28px;
  }
  .t-button--theme-primary {
    width: 60px;
    height: 28px;
    opacity: 1;
    border-radius: 3px;
    background: rgba(30, 117, 254, 1);
  }
}
:deep(.dialogDel .t-dialog__wrap .t-dialog__position .t-dialog) {
  padding: 22px 22px 18px 22px;
  .t-icon.t-is-info {
    color: rgba(30, 117, 254, 1) ;
  }
  .t-dialog__body__icon {
    display: none;
  }
  .t-dialog__footer {
    padding-top: 31px;
    .t-dialog__cancel {
      background-color: white;
      border: none;
      width: 60px;
      height: 28px;
    }
    .t-dialog__confirm {
      width: 60px;
      height: 28px;
      opacity: 1;
      border-radius: 3px;
      background: rgba(30, 117, 254, 1);
    }
    .t-dialog__confirm:hover {
      background: var(--Brand-Brand6-Hover, #458DFF) !important;
      color: var(--text-icon-font-wh-190-anti, rgba(255, 255, 255, 0.90)) !important;
    }
  }
}
</style>

